package com.ruoyi.web.controller.ring.app;

import cn.hutool.core.convert.Convert;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.ring.domain.RingSportDetail;
import com.ruoyi.ring.domain.dto.RingSportDetailAddDTO;
import com.ruoyi.ring.service.IRingSportDetailService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 运动明细 （APP）
 */
@RestController
@RequestMapping("/ring/app/ring_sport_detail")
public class AppSportDetailController extends BaseController
{
    @Resource
    private IRingSportDetailService ringSportDetailService;

    /**
     * 上报运动详细信息 app
     * @return
     */
    @PostMapping("/add")
    public AjaxResult addDetail(@RequestBody RingSportDetailAddDTO addDTO)
    {
        String deviceSn = addDTO.getDeviceSn();
        try {
            List<RingSportDetailAddDTO.StressDTO> stressDTOList = addDTO.getStress();
            stressDTOList.forEach(stressDTO -> {
                Date dailyValue = stressDTO.getDailyValue();
                RingSportDetail sportDetail = ringSportDetailService.selectOneRingSportDetail(Builder.of(RingSportDetail::new).
                        with(RingSportDetail::setDeviceSn, deviceSn).
                        with(RingSportDetail::setHistoryDay, dailyValue).build());
                RingSportDetail ringSportDetail = Convert.convert(RingSportDetail.class,stressDTO);
                if(sportDetail != null){
                    ringSportDetail.setId(sportDetail.getId());
                    ringSportDetail.setDeviceSn(deviceSn);
                    ringSportDetail.setHistoryDay(dailyValue);
                    ringSportDetailService.updateRingSportDetail(ringSportDetail);
                }else {
                    ringSportDetail.setDeviceSn(deviceSn);
                    ringSportDetail.setHistoryDay(dailyValue);
                    ringSportDetailService.insertRingSportDetail(ringSportDetail);
                }
            });
            return AjaxResult.success();
        }catch (Exception e){
            throw new RuntimeException("上报运动详细信息失败！");
        }
    }

}
